package org.dromara.system.service.impl.pay;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessException;
import org.dromara.system.domain.ZfbConfig;
import org.dromara.system.domain.bo.InitGetMachineBo;
import org.dromara.system.domain.bo.InitPayMemberBo;
import org.dromara.system.enums.MachineConstant;
import org.dromara.system.service.IZfbConfigService;
import org.dromara.system.util.AlipayUtil;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Slf4j
@Service
@RequiredArgsConstructor
public class AliPayApp extends AbstractPayService {

    private final static String VIP_NOTIFY_URL = "http://121.40.66.143:4330/system/memberRecords/openMemberShip/callBak/alipay";
    private final static String GET_MACHINE_NOTIFY_URL = "";
    private final IZfbConfigService zfbConfigService;
    private final AlipayUtil alipayUtil;

    @Override
    public String initPayMember(InitPayMemberBo initPayMemberBo) {
        ZfbConfig zfbConfig = zfbConfigService.lambdaQuery().eq(ZfbConfig::getUserId, MachineConstant.ADMIN).one();
        BusinessException.isNull(zfbConfig, "未查询到支付宝相关配置！");
        BigDecimal memberPrice = initPayMemberBo.getSysUserMemberConfig().getMemberPrice();
        AlipayTradeAppPayResponse response = null;
        try {
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            //构建请求参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", initPayMemberBo.getMemberRecordsBo().getNo());
            bizContent.put("total_amount", memberPrice);
            bizContent.put("subject", "图钉科技");
            bizContent.put("product_code", "QUICK_MSECURITY_PAY");
            request.setNotifyUrl(VIP_NOTIFY_URL);
            request.setBizContent(bizContent.toString());
            AlipayClient alipayClient = alipayUtil.getAlipayClient(zfbConfig);
            response = alipayClient.sdkExecute(request);
            if (response != null && response.isSuccess()) {
                log.info("调用成功{}", response.getBody());
                return response.getBody();
            } else {
                BusinessException.isTrue(Boolean.TRUE, "支付宝调用失败！");
            }
        } catch (Exception e) {
            BusinessException.isTrue(Boolean.TRUE, "支付宝调用失败！");
        }
        return "";
    }

    @Override
    public String initPayGetMachine( InitGetMachineBo initPayMemberBo) {
        BusinessException.isTrue(Boolean.TRUE,"支付宝支付暂未开通");
        return "";
    }
}
